package com.lili.math;

/**
 * @Auther: 李 力
 * @Date: 2024/8/3
 * @Description: 各位相加
 * @version: 1.0
 */
public class LeetCode258 {
    /*
     *  时间复杂度: O(num.len)
     *  空间复杂度: O(1)
     */
    public static int addDigits(int num) {
        String string = Integer.toString(num);
        if (string.length() == 1) {
            return num;
        }
        int result = 0;
        for (int i = 0; i < string.length(); i++) {
            int r = Integer.parseInt(String.valueOf(string.charAt(i)));
            result = result + r;
        }
        return addDigits(result);
    }

    //更优解
    public static int addDigits2(int num) {
        //如果num小于10了，那么返回数就是自己
        while (num >= 10) {
            int sum = 0;
            while (num > 0) {
                sum = sum + num % 10;
                num = num / 10;
            }
            num = sum;
        }
        return num;
    }
}
